import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ListenerSample extends StatefulWidget {
  @override
  _ListenerSampleState createState() => _ListenerSampleState();
}

class _ListenerSampleState extends State<ListenerSample> {

  int _downCounter = 0;
  int _upCounter = 0;
  double x = 0.0;
  double y = 0.0;

  // 手指按下时触发
  void _incrementDown(PointerEvent details) {
    _updateLocation(details);
    setState(() {
      _downCounter++;
    });
  }
  // 手指抬起时触发
  void _incrementUp(PointerEvent details) {
    _updateLocation(details);
    setState(() {
      _upCounter++;
    });
  }
  // 手指在区域内移动时触发
  void _updateLocation(PointerEvent details) {
    setState(() {
      x = details.position.dx;
      y = details.position.dy;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: ConstrainedBox(
              constraints: new BoxConstraints.tight(const Size(300.0, 200.0)),
              // 使用Listener接受指针事件
              child: Listener(
                  onPointerDown: _incrementDown,
                  onPointerMove: _updateLocation,
                  onPointerUp: _incrementUp,
                  child: Container(
                      color: Colors.lightBlueAccent,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          const Text('手势按下并且抬起的次数:'),
                          Text(
                            '$_downCounter次按下\n$_upCounter次抬起',
                          ),
                          Text(
                            '手指正处于位置(${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})',
                          ),
                        ],
                      ))))),
    );
  }
}